package com.lishe.lishe.lishe.module.mall.fragment;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.lishe.lishe.R;
import com.lishe.base.common.base.BaseFragment;
import com.lishe.lishe.lishe.module.commonclass.WebActivity;
import com.lishe.lishe.lishe.module.mall.activity.ClassifySearchActivity;
import com.lishe.lishe.lishe.module.mall.adapter.GlideImageLoader;
import com.lishe.lishe.lishe.module.mall.adapter.MallClassifyAdapter;
import com.lishe.lishe.lishe.module.mall.adapter.MallMaybeLikeAdapter;
import com.lishe.lishe.lishe.module.mall.adapter.MallRecyClerViewAdapter;
import com.lishe.lishe.lishe.module.mall.adapter.MallSelectActivityAdapter;
import com.lishe.lishe.lishe.module.mall.adapter.MallTitleActivityAdapter;
import com.lishe.lishe.lishe.module.mall.adapter.MallValuseAdapter;
import com.lishe.lishe.lishe.module.mall.bean.MallGoods;
import com.lishe.lishe.lishe.module.mall.bean.MallItemObject;
import com.lishe.lishe.lishe.module.mall.bean.MallObject;
import com.lishe.lishe.lishe.module.mall.bean.WrapContentLinearLayoutManager;
import com.lishe.lishe.lishe.module.mall.http.HttpMall;
import com.lishe.lishe.lishe.module.search.activity.HomeSearchActivity;
import com.lishe.lishe.lishe.module.shopingcart.activity.ShopCarActivity;
import com.lishe.lishe.lishe.utils.LogUtil;
import com.lishe.lishe.lishe.utils.SharedPreferencesUtils;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * Created by shino on 2017/11/6.
 * 商城首页
 */

public class HomeFragment extends BaseFragment implements View.OnClickListener {

    private RecyclerView mRecyclerView;
    private SmartRefreshLayout mRefreshLayout;
    private MallRecyClerViewAdapter adapter;

    private MallObject mallObjectLun = new MallObject();//轮播图数据
    private MallObject mallObjectLove = new MallObject();//猜你喜欢数据
    private List<MallObject> mallObjects = new ArrayList<>();//首页模块

    private int page = 1;
    private int pageSize = 10;
    private int totalPage = 0;

    //-----------不同类型的adapter-----------------
    private MallTitleActivityAdapter mallTitleActivityAdapter;//首页大推荐
    private MallClassifyAdapter mallClassifyAdapter;//导航分类
    private MallValuseAdapter mallValuseAdapter;//超值专区
    private MallSelectActivityAdapter mallSelectActivityAdapter;//精选活动
    private MallMaybeLikeAdapter mallMaybeLikeAdapter;//猜你喜欢
    private View mTop;
    private int mCurrentY;
    private View mErrorLayout;
    private View rootView;// cache fragment view

    public static void jump(Activity activity) {
        Intent intent = new Intent(activity, HomeFragment.class);
        activity.startActivity(intent);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        adapter = new MallRecyClerViewAdapter(getActivity(), mallObjects);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_home, null);
            initView(rootView);
            rootView.setOnTouchListener(this);

            //取出保存的data展示
            String data = SharedPreferencesUtils.getHomeData();
            if (data != null && !"".equals(data)) {
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    parseData(jsonObject);
                    notifyAdapter();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        return rootView;
    }

    @SuppressLint("ClickableViewAccessibility")
    @TargetApi(Build.VERSION_CODES.M)
    private void initView(View v) {
        mErrorLayout = v.findViewById(R.id.error_layout);
        v.findViewById(R.id.error_retry).setOnClickListener(this);
        v.findViewById(R.id.search).setOnClickListener(this);
        mTop = v.findViewById(R.id.top);
        mTop.setOnClickListener(this);

        mRecyclerView = v.findViewById(R.id.recyclerView);
        mRefreshLayout = v.findViewById(R.id.refreshlayout);
        WrapContentLinearLayoutManager layoutManager = new WrapContentLinearLayoutManager(getActivity());
        layoutManager.setAutoMeasureEnabled(true);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(adapter);
        //增加返回顶部按钮，当滑动达到第三屏的时候在屏幕右下角显示按钮
        mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                mCurrentY += dy;
                if (mCurrentY > 4430) {
                    mTop.setVisibility(View.VISIBLE);
                } else {
                    mTop.setVisibility(View.GONE);
                }
            }
        });
        mRecyclerView.setOnTouchListener(//避免更新数据是刷新闪退
                new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        if (mRefreshLayout.isRefreshing()) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                }
        );

        mRefreshLayout.setEnableLoadmore(true);
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.setLoadmoreFinished(false);
                page = 1;
                totalPage = 0;
                if (mallObjectLove.getItemObject() != null) {
                    mallObjectLove.getItemObject().clear();
                }
                getMallMain();
            }
        });
        mRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                if (page <= totalPage) {
                    refreshlayout.setLoadmoreFinished(false);
                    getMaybeLove();
                } else {
                    refreshlayout.finishLoadmore();
                    refreshlayout.setLoadmoreFinished(true);
                }
            }
        });
        mRefreshLayout.autoRefresh();
    }

    /**
     * 获取首页数据
     */
    private void getMallMain() {
        HttpMall.getMallMain(responseHandler);
    }

    /**
     * 获取首页-猜你喜欢
     */
    private void getMaybeLove() {
        try {
            HttpMall.getMaybeLove(page + "", pageSize + "", "getMaybeLove", maybeLoveRespon);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    AsyncHttpResponseHandler maybeLoveRespon = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String data = new String(responseBody);
            mRefreshLayout.finishLoadmore();
            LogUtil.i("猜你喜欢", data);
            try {
                JSONObject json = new JSONObject(data);
                if (json.optInt("errcode") == 0 && json.optInt("result") == 100) {
                    JSONObject dataObject = json.optJSONObject("data");
                    MallItemObject mallItemObject;
                    if (page == 1) {
                        mallObjectLove = JSON.parseObject(dataObject.toString(), MallObject.class);
                        mallItemObject = new MallItemObject();
                        mallObjects.add(mallObjectLove);
                    } else {
                        mallItemObject = mallObjectLove.getItemObject().get(0);
                    }
                    JSONArray items = dataObject.optJSONArray("items");

                    totalPage = dataObject.optInt("totalPage");
                    page = page + 1;
                    Log.e("page"+page,"totalPage"+totalPage);
                    for (int i = 0; i < items.length(); i++) {
                        JSONObject item = items.optJSONObject(i);
                        MallGoods mallGoods = new MallGoods();
                        mallGoods = JSON.parseObject(item.toString(), MallGoods.class);
                        mallItemObject.getMallGoodsItem().add(mallGoods);
                    }
                    mallObjectLove.getItemObject().add(mallItemObject);
                    mallMaybeLikeAdapter = null;
                    mallMaybeLikeAdapter = new MallMaybeLikeAdapter(getActivity(), mallObjectLove.getItemObject().get(0).getMallGoodsItem());
                    mallObjectLove.setAdapter(mallMaybeLikeAdapter);
                    Collections.sort(mallObjects, new Comparator<MallObject>() {
                        @Override
                        public int compare(MallObject mallObject, MallObject t1) {//取倒叙
                            return t1.getSort().compareTo(mallObject.getSort());
                        }
                    });
                }
                notifyAdapter();
            } catch (Exception e) {
                e.printStackTrace();
                notifyAdapter();
//                toast("数据异常" + data);
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            toast("网络或服务器异常！");
            mRefreshLayout.finishLoadmore();
            notifyAdapter();
        }
    };
    AsyncHttpResponseHandler responseHandler = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            mRefreshLayout.finishRefresh();
            String result = new String(responseBody);
            getMaybeLove();
            LogUtil.i("商城首页", result);
            try {
                JSONObject jsonObject = new JSONObject(result);
                if (jsonObject.optInt("errcode") == 0 && jsonObject.optInt("result") == 100) {
                    SharedPreferencesUtils.saveHomeData(result);
                    parseData(jsonObject);
                } else {
                    toast(jsonObject.optString("msg"));
                }
                notifyAdapter();
            } catch (JSONException e) {
                notifyAdapter();
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            mRefreshLayout.finishRefresh();
            notifyAdapter();
            mRefreshLayout.setVisibility(View.GONE);
            mErrorLayout.setVisibility(View.VISIBLE);
        }
    };

    private void parseData(JSONObject jsonObject) {
        mallObjects.clear();
        JSONArray dataArray = jsonObject.optJSONArray("data");
        for (int j = 0; j < dataArray.length(); j++) {
            JSONObject data = dataArray.optJSONObject(j);
            MallObject mallObject = JSON.parseObject(data.toString(), MallObject.class);
            JSONArray codeData = data.optJSONArray(mallObject.getCode());
            if (codeData != null) {
                for (int i = 0; i < codeData.length(); i++) {
                    JSONObject json = codeData.optJSONObject(i);
                    MallItemObject mallItemObject = new MallItemObject();
                    mallItemObject = JSON.parseObject(json.toString(), MallItemObject.class);
                    if (mallObject.getStyle().equals("activityStyle")) {//精选活动
                        JSONArray itemArray = json.optJSONArray("items");
                        mallItemObject.getMallGoodsItem().clear();
                        for (int k = 0; k < itemArray.length(); k++) {
                            JSONObject item = itemArray.optJSONObject(k);
                            MallGoods mallGoods = new MallGoods();
                            mallGoods = JSON.parseObject(item.toString(), MallGoods.class);
                            mallItemObject.getMallGoodsItem().add(mallGoods);
                        }
                        JSONObject moreObject = json.optJSONObject("more");
                        if (moreObject != null) {
                            MallGoods more = new MallGoods();
                            more.setImage_default_id(moreObject.optString("more_goods_img"));
                            more.setItem_id(moreObject.optString("activity_config_id"));
                            more.setTitle(moreObject.optString("cat_name"));
                            mallItemObject.getMallGoodsItem().add(more);
                        }
                    }
                    mallObject.getItemObject().add(mallItemObject);
                }
            }
            if (mallObject.getStyle().equals("indexBannerStyle")) {
                mallObjectLun = mallObject;
            } else {
                if (mallObject.getStyle().equals("recommendStyle")) {//活动主题
                    mallTitleActivityAdapter = null;
                    mallTitleActivityAdapter = new MallTitleActivityAdapter(getActivity(), mallObject.getItemObject());
                    mallObject.setAdapter(mallTitleActivityAdapter);
                }
                if (mallObject.getStyle().equals("cateStyle")) {//导航栏
                    mallClassifyAdapter = null;
                    mallClassifyAdapter = new MallClassifyAdapter(getActivity(), mallObject.getItemObject());
                    mallObject.setAdapter(mallClassifyAdapter);

                }
                if (mallObject.getStyle().equals("valueStyle")) {//超值专区
                    mallValuseAdapter = null;
                    mallValuseAdapter = new MallValuseAdapter(getActivity(), mallObject.getItemObject());
                    mallObject.setAdapter(mallValuseAdapter);
                }
                if (mallObject.getStyle().equals("activityStyle")) {//精选活动
                    mallSelectActivityAdapter = null;
                    mallSelectActivityAdapter = new MallSelectActivityAdapter(getActivity(), mallObject.getItemObject());
                    mallObject.setAdapter(mallSelectActivityAdapter);
                }
                mallObjects.add(mallObject);
            }
        }
        View view = initHeaderView();
        if (view != null) {
            adapter.addHeaderView(view);
        }
    }

    private void notifyAdapter() {
        //1秒后刷新
        LogUtil.i("Mallfragment刷新", "0");
        i = 0;
        notifyHandler.removeCallbacks(runnable);
        notifyHandler.postDelayed(runnable, 0);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        notifyHandler.removeCallbacks(runnable);
    }

    private View initHeaderView() {
        if (getActivity() == null) {
            return null;
        }
        View v = getActivity().getLayoutInflater().inflate(R.layout.item_banner, null, false);
        Banner banner = v.findViewById(R.id.banner);
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //设置图片集合
        banner.setImages(mallObjectLun.getItemObject());
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.Default);
        //设置标题集合（当banner样式有显示title时）
//        banner.setBannerTitles(titles);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(5000);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                final MallItemObject mallItemObject = mallObjectLun.getItemObject().get(position);
                if ("0".equals(mallItemObject.getType())) {
                    Intent intent = new Intent(getActivity(), ClassifySearchActivity.class);
                    intent.putExtra(ClassifySearchActivity.CATEID, mallItemObject.getValue());
                    intent.putExtra(ClassifySearchActivity.TITLE, mallItemObject.getName());
                    getActivity().startActivity(intent);
                } else if ("1".equals(mallItemObject.getType())) {
                    if (!TextUtils.isEmpty(mallItemObject.getLink_url())) {
                        WebActivity.jump(getActivity(), mallItemObject.getLink_url(), mallItemObject.getName());
                    }
                }
            }
        });
        //banner设置方法全部调用完毕时最后调用
        banner.start();
        return v;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.search:
                Intent intent = new Intent(getActivity(), HomeSearchActivity.class);
                intent.putExtra(HomeSearchActivity.SEARCH_FROM, "Home");
                startActivity(intent);
                break;
            case R.id.goods_cart:
                ShopCarActivity.jump(getActivity());
                break;
            case R.id.top:
                mCurrentY = 0;
                mTop.setVisibility(View.GONE);
                mRecyclerView.scrollToPosition(0);
                break;
            case R.id.error_retry:
                mRefreshLayout.autoRefresh();
                mErrorLayout.setVisibility(View.GONE);
                mRefreshLayout.setVisibility(View.VISIBLE);
                break;
        }
    }

    int i = 0;
    Handler notifyHandler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            Log.e("刷新", "0--" + i);
            i = i + 1;
//            notifyHandler.postDelayed(this, 1000);
            if(getActivity()==null){
                return;
            }
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < mallObjects.size(); i++) {
                        if (mallObjects.get(i).getAdapter() != null) {
                            mallObjects.get(i).getAdapter().notifyDataSetChanged();
                        }
                    }
                    adapter.notifyDataSetChanged();
                }
            });
            if (i == 5) {
                notifyHandler.removeCallbacks(this);
            }
        }
    };
}
